#include <stdio.h>
#include <stdlib.h>

#include "importer.h"
#include "triangle_list.h"
#include "exporter.h"
#include "edge_list.h"
#include "manager.h"
#include "triangulation.h"
#include "linker.h"

#define DEBUG

int main(int argc, char ** argv){
	PointList * inputPoints;
	PointList ** dividedPoints;
	EdgeList ** convexHulls;
	TriangleList ** localWires;
	TriangleList * globalWire;
	TriangleList * connectionWire;
	int segments, i;
	char * outputFileName;

	if(argc < 3){
		printf("Too few parameters.\n");
		return 1;
	}

	segments = atoi(argv[1]);
	outputFileName = argv[2];
	
	printf("Loading points...\n");
	
	inputPoints = load(outputFileName);
	if(inputPoints == NULL)
		return 1;

	convexHulls = (EdgeList **)malloc(segments * sizeof(EdgeList*));
	for(i = 0; i < segments; i++)
		convexHulls[i] = newEdgeList();

	localWires = (TriangleList **)malloc(segments * sizeof(TriangleList*));

	globalWire = newTriangleList();
	connectionWire = newTriangleList();

	printf("Sorting points...\n");
	sortPointList(inputPoints);

	printf("Dividing point cloud...\n");
	dividedPoints = dividePoints(inputPoints, segments);

	printf("Triangulation started...\n");
	for(i = 0; i < segments; i++){
		localWires[i] = triangulation(dividedPoints[i], convexHulls[i]);
		printf("Triangles created for segment %d: %ld\n", i, localWires[i]->length);
		addAllTriangles(globalWire, localWires[i]);
	}

#ifdef DEBUG
	if(saveGnuPlotFormat(globalWire, "local_wires.txt") == -1)
		return 1;
#endif

	printf("Triangulation finished. Merging...\n");

#ifdef DEBUG
	saveEdgeLists(convexHulls, segments, "convex_hulls.txt");
#endif

	connectionWire = mergeAllTriangulations(convexHulls, segments);

#ifdef DEBUG
	if(saveGnuPlotFormat(connectionWire, "connection_wire.txt") == -1)
		return 1;
#endif

	addAllTriangles(globalWire, connectionWire);

	printf("Saving wire...\n");

	if(saveGnuPlotFormat(globalWire, "final_wire.txt") == -1)
		return 1;

	printf("Freeing resources...\n");

	freePointList(inputPoints);

	for(i = 0; i < segments; i++){
		freePointList(dividedPoints[i]);
	}

	free(dividedPoints);
	freeEdgeList(convexHulls[0]);
	free(convexHulls);
	free(localWires);
	freeTriangleList(globalWire);

	printf("Done...\n");

	return 0;
}


